package gov.nist.healthcare.testframework.communication.mllp.server;

import gov.nist.healthcare.core.MalformedMessageException;
import gov.nist.healthcare.core.message.HL7Message;
import gov.nist.healthcare.core.message.v2.er7.Er7Message;
import gov.nist.healthcare.testframework.communication.MllpUtils;
import gov.nist.healthcare.testframework.communication.server.ServerThread;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;

public class MLLPEr7ServerThread extends ServerThread {

    private static final Logger logger = Logger.getLogger(MLLPEr7ServerThread.class.getName());

    @Override
    public boolean getSecure() {
        return false;
    }

    @Override
    public HL7Message getMessage() {
        HL7Message message = null;
        try {
            InputStream in = socket.getInputStream();
            String msg = null;
            msg = MllpUtils.extractMessage(in);
            message = new Er7Message(msg);
        } catch (IOException ioe) {
            logger.debug("Exception when reading the input stream", ioe);
        } catch (MalformedMessageException mme) {
            logger.debug("Exception when creating an Er7 message", mme);
        }
        return message;
    }

    public HL7Message processIncoming() {
        HL7Message message = null;
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            // Get the message
            StringBuffer sb = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                sb.append(inputLine).append("\n");
            }
            // Create the message
            Er7Message er7 = null;
            try {
                er7 = new Er7Message(sb.toString());
                message = er7;
            } catch (MalformedMessageException mme) {
                logger.debug("Exception when creating an Er7 message", mme);
            }
        } catch (IOException ioe) {
            logger.debug("Exception when reading the input stream", ioe);
        }
        return message;
    }

    @Override
    public String encode(HL7Message message) {
        return MllpUtils.wrapMessage(message);
    }

    @Override
    public ServerThread restart() {
        return new MLLPEr7ServerThread();
    }
}
